<template>
    <div>
        
   <div><span>文章标题</span><el-input class="title" v-model="title"/></div>
       <!-- 图片上传组件辅助-->
      
    <!-- <el-upload class="avatar-uploader" :action="uploadUrl" name="img" :on-success="uploadSuccess" >
    </el-upload> -->
        
    <input type="file" ref="imgupload" style="display:none" @input="uploadImg" />
     <button @click="$refs.imgupload.click()" style="display:none"
     class="uploader">上传</button>


        <quill-editor 
	   class="ql-editor"
	   v-model="content" 
	   ref="QuillEditor" 
	   :options="editorOption" 
	   @blur="onEditorBlur($event)" 
	   @focus="onEditorFocus($event)"
	   @change="onEditorChange($event)">
	</quill-editor>

    <div class="cover">
        <div>文章封面</div>
        <!-- 上传组件 -->
         
     
        <input type="file" style="display: none" ref="input" @input="upload" >
          <el-button @click="$refs.input.click()" type="primary">上传封面</el-button>
      
        
       <img src="" alt="暂无图片" id="cover" style="width: 200px;height: 150px;">


        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
   <!--发布文章  -->
   <el-button type="primary" class="publish" @click="publish">发布文章</el-button>
    </div>
	
</template>
 
<script>
import reqPublish from '@/api/commen/publish'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import Quill from 'quill' // 引入编辑器
import tooroptions from '@/utils/options/quilloption'
import allConf from '@/conf/allconf'
// // 自定义字体大小
// const Size = Quill.import('attributors/style/size')
// Size.whitelist = ['10px', '12px', '16px', '18px', '20px', '30px', '32px']
// Quill.register(Size, true)
// // 自定义字体类型
// var fonts = ['SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial', 'sans-serif']
// var Font = Quill.import('formats/font')
// Font.whitelist = fonts
// Quill.register(Font, true)






export default {
    components: { quillEditor },
    data() {
        return {
            //标题
         title:'',
         fileList:[],
         cover:{},
         dialogImageUrl: '',
         dialogVisible: false,
         disabled: false,

         //上传完之后返回来的图片数组
         resImgs:[],
         //失去焦点后的图片数组
         noblurImgs:[],

         //
	       content: `<p></p>`, //双向数据绑定数据
		  // 富文本编辑器配置
	      editorOption: {
	        modules: {
		          toolbar: {
               container:tooroptions,
               //处理
               handlers: {
               image: function (value) {
                 if (value) {
                   // 调用element的图片上传组件
                   //document.querySelector('.avatar-uploader input').click()
                   document.querySelector('.uploader').click()
                 } else {
                   this.quill.format('image', false)
                 }
                }
              }
              },
              
            
		        },
		        placeholder: '请输入正文'
	      	} ,
          //图片上传路径
          uploadUrl: allConf.BaseURL+"/upload/contentimg"
	      }
	  		},
    methods: {
       // 失去焦点事件
		  onEditorBlur(quill) {
		    //console.log(this.content);
        let length = document.querySelectorAll(".ql-editor img").length
        if(length){
          let images =document.querySelectorAll(".ql-editor img")
          images.forEach(item=>{
            this.noblurImgs.push(item.src.substr(item.src.lastIndexOf("/")+1))
          })
        }
          
        var removeImgs = this.resImgs.filter( (i)=>
        this.noblurImgs.every( (e)=> e != i ) )
        if(removeImgs){
          //则吧不一致的删除了
          removeImgs.forEach(item=> reqPublish.removeImg(item))
          //再把该图片从数组中移除
         //let index =  this.noblurImgs.findIndex(item)
        // console.log(index);
        // this.noblurImgs.splice(index,1)
        } 

		  },
		// 获得焦点事件
		  onEditorFocus(quill) {
		    console.log('editor focus!', quill)
		  },
		// 准备富文本编辑器
		  onEditorReady(quill) {
		    console.log('editor ready!', quill)
		  },
		// 内容改变事件
		  onEditorChange({ quill, html, text }) {
		    console.log('editor change!', quill, html, text)
		    this.content = html
		  },
 
    //自定义上传组件
  async upload(){
    //  const data = new FormData()
    //  data.append('file',this.$refs.input.files[0])
      this.cover = this.$refs.input.files[0]
    // this.cover = data
       const file =this.$refs.input.files[0]
       var filereadr = new FileReader()
       filereadr.readAsDataURL(file)
       filereadr.onload=function(){
         var img = document.getElementById('cover')
         img.src = filereadr.result
       }
  	},

   //上传内容图片
   async uploadImg(){
      const data = new FormData()
      data.append('file',this.$refs.imgupload.files[0])
      const res = await reqPublish.uploadImg(data)
      if(res.code==200){
         // 获取富文本组件实例
      let quill = this.$refs.QuillEditor.quill
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, 'image', res.data)
        // 调整光标到最后
        quill.setSelection(length + 1)
        //将图片地址放入数组中
        this.resImgs.push(res.data.substr(res.data.lastIndexOf("/")+1))
      } else {
        // 提示信息，需引入Message
        this.$message.error('图片插入失败！')
      }
      },

   //发布文章
   async publish(){
    if(this.title=="" || this.content=="" || this.cover==null){
      this.$message("内容不能为空！")
      return;
    }
     
    const userid = this.$store.state.userinfo.user.id;

     const files = []
     const form = new FormData()
     form.append("cover",this.cover)
     form.append("title",this.title)
     form.append("content",this.content)

     const res = await reqPublish.publish(userid,form)
     if(res.code==200){
      this.$message({type:'success',message:'发布成功，等待审核!'})
     }else this.$message(res.message)
   
    },


    },
 

 
  



    }

</script>

<style scoped lang="less">
body{
    overflow: hidden;
}
/**文章标题 */
.title{
    width: 620px;
}


/*加上height和滚动属性就可以，滚动条样式是系统默认样式，可能不同*/
.ql-toolbar.ql-snow .ql-picker.ql-expanded .ql-picker-options {
  border-color: #ccc;
  height: 125px;
  overflow: auto;
}
.ql-editor{
    height:300px;
   /* overflow: hidden; */
}

.el-container.is-vertical{
  padding-bottom: 100px;
}
/*发布按钮 */
.publish{
  position: relative;
  bottom: 30px;
  float: right;
  margin-right: 200px;
  // margin-bottom: 80px;
  width: 200px;
  height: 50px;
}
.uploadimg{
 width: 50px;
 height: 50px;
 border: 2px solid rgb(244, 240, 240);
 background-color: rgb(249, 255, 252);
 text-align: center;
}
.uploadimg:hover{
  border-color: #66b1ff;
}

</style>
